package cloud.seri.iot.aliyun.service


import com.aliyun.openservices.iot.api.message.api.MessageClient
import com.aliyun.openservices.iot.api.message.callback.MessageCallback
import com.aliyun.openservices.iot.api.message.entity.Message
import com.fasterxml.jackson.databind.ObjectMapper
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import javax.annotation.PostConstruct

@Service
class ClientMessageService(private val client: MessageClient, private val objectMapper: ObjectMapper)
{

    private val log = LoggerFactory.getLogger(ClientMessageService::class.java)


    @PostConstruct
    fun start()
    {
        client.connect { MessageCallback.Action.CommitSuccess }
        client.setMessageListener {
            log.info("topic: ${it.message.topic} message:${it.message} ")
            if (it.message.topic.endsWith("/thing/lifecycle"))
            {
                onDeviceLifecycleChanged(it.message)
            }
            if (it.message.topic.startsWith("/as/mqtt/status/"))
            {
                onDeviceStatusChanged(it.message)
            }
            MessageCallback.Action.CommitSuccess
        }

//
//        client.setMessageListener("/as/mqtt/status/#") {
//            log.info("topic: ${it.message.topic} message:${it.message} ")
//            onDeviceStatusChanged(it.message)
//        }
    }

    private fun onDeviceStatusChanged(message: Message): MessageCallback.Action
    {
        log.info("设备状态改变 $message")
        return MessageCallback.Action.CommitSuccess
    }

    private fun onDeviceLifecycleChanged(message: Message): MessageCallback.Action
    {
        log.info("设备生命周期变换 $message")


        return MessageCallback.Action.CommitSuccess
    }
}
